<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>异步编程的传统方法</title>
</head>
<body>
    <h1>异步编程的传统方法</h1>

    <script>
        // 回调函数
        function loadScript(src, callback) {
            let script = document.createElement('script');
            script.src = src;
            script.onload = () => callback(null, script);
            script.onerror = () => callback(new Error(`加载脚本 ${src} 失败`));
            document.head.append(script);
        }

        loadScript('script1.js', function(error, script) {
            if (error) {
                console.log('Error: ' + error);
            } else {
                // 加载下一个脚本
                loadScript('script2.js', function(error, script) {
                    if (error) {
                        console.log('Error: ' + error);
                    } else {
                        // 继续加载更多脚本...
                    }
                });
            }
        });

        // 事件监听
        const button = document.createElement('button');
        button.textContent = '点击我';
        document.body.appendChild(button);

        button.addEventListener('click', function handler1() {
            console.log('第一个处理函数');
        });

        button.addEventListener('click', function handler2() {
            console.log('第二个处理函数');
        });

        // 发布/订阅模式
        class EventEmitter {
            constructor() {
                this.events = {};
            }

            on(event, callback) {
                if (!this.events[event]) {
                    this.events[event] = [];
                }
                this.events[event].push(callback);
            }

            emit(event, ...args) {
                const callbacks = this.events[event];
                if (callbacks) {
                    callbacks.forEach(callback => callback.apply(this, args));
                }
            }
        }

        const emitter = new EventEmitter();
        emitter.on('data', function(data) {
            console.log('收到数据:', data);
        });
        emitter.emit('data', 'Hello World');
    </script>
</body>
</html> 